package cn.shangqizhenshuai.Class;

import cn.shangqizhenshuai.Http.HttpCore;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import java.util.HashMap;

public class Ting55 {

    /**
     * 需要下载的rul地址从多少级下载到多少级
     * @param url 地址
     * @param startep 开始第几集
     * @param endep 结束第几集
     */

    /**
     *
     * @param url 下载的目录地址
     * @param startep 起始多少级
     * @param endep 结束多少及
     * @param saveDir 下载文件保存的目录 文件名默认是级数
     * @throws XPatherException
     */
    public void getout(String url,int startep,int endep,String saveDir) throws XPatherException, InterruptedException {
        //第几集和每一集的连接
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        //
        HashMap<String, String> stringStringHashMap1 = new HashMap<>();
        //得到页面
        String newget = HttpCore.newget(url, null);
        //转化为节点
        TagNode resxpath = HttpCore.resxpath(newget);
        Object[] objects = resxpath.evaluateXPath("//div[@class='plist']");
        //每一集的连接
        Object[] objects1 = ((TagNode) objects[0]).evaluateXPath("//li");
        for (Object o : objects1) {
            String href= "https://ting55.com";
            Object[] objects2 = ((TagNode) o).evaluateXPath("//a");
            href+= ((TagNode) objects2[0]).getAttributeByName("href");
            String ep = ((TagNode) objects2[0]).getText().toString();
            stringStringHashMap.put(ep,href);
        }
        //获取下载的输出流
        //audio
        //下载过于暴力后会限制现在 最多一次下7个下载6个就行
        int ll = 1 ;
        int temp = startep;
        for (; temp <=endep ; temp++) {
            if(ll%5==0){
                //暂停一会继续下载目前没有好办法
                Thread.sleep(60000);
            }
            String s = stringStringHashMap.get(temp + "");
            System.out.println("正在访问"+s);
            String newget1 = HttpCore.newget(s, null);
            TagNode resxpath1 = HttpCore.resxpath(newget1);
            Object[] objects2 = resxpath1.evaluateXPath("//body");
            Object[] objects3 = ((TagNode) objects2[0]).evaluateXPath("/script[@type='text/javascript']");
            String toString = ((TagNode) objects3[0]).getText().toString();
            String[] split = toString.split(";");
            String s1 = split[0];
            String substring = s1.substring(s1.lastIndexOf("{")+1, s1.lastIndexOf("}"));
            String[] split1 = substring.split(":");
            String s2 = split1[1]+":"+split1[2];
            s2 =  s2.substring(1,s2.length() - 1);
            System.out.println(s2);
            //split1[0] 后缀
            //找到文件后缀
            System.out.println("已经获得真实下载地址正在下载");
            //保存在本地

            HttpCore.downloadByNIO2(s2,saveDir,temp+"."+split1[0]);
            System.out.println("文件保存成功目录："+saveDir+"\\"+temp+"."+split1[0]);
            ll++;
        }

    }
}

